package utils;

import net.minidev.json.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map.Entry;

public class MyHttpUtils {

	private final Logger log = LoggerFactory.getLogger(MyHttpUtils.class);

	public CloseableHttpClient httpClient;

	public MyHttpUtils() {
		// TODO Auto-generated constructor stub
		httpClient = HttpClients.createDefault();
	}

	public static void main(String[] args) throws Exception {

	}

	// 处理GET消息
	public JSONObject doGet(String url, HashMap<String, String> headers) {

		JSONObject jsonObject = new JSONObject();

		try {
			HttpGet httpGet = new HttpGet(url);
			for (Entry<String, String> entry : headers.entrySet()) {
				httpGet.addHeader(entry.getKey(), entry.getValue());
			}

			CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

			jsonObject.put("code", httpResponse.getStatusLine().getStatusCode());
			jsonObject.put("message", EntityUtils.toString(httpResponse.getEntity()));
		} catch (Exception e) {
			// TODO: handle exception
			log.error("doGet Method Exception - " + url + headers + " - " + e.toString());
		}

		return jsonObject;
	}

	// 处理POST消息
	public JSONObject doPost(String url, HashMap<String, String> headers, String body) {

		JSONObject jsonObject = new JSONObject();

		try {
			HttpPost httpPost = new HttpPost(url);
			for (Entry<String, String> entry : headers.entrySet()) {
				httpPost.addHeader(entry.getKey(), entry.getValue());
			}

			// 构建消息实体
			StringEntity entity = new StringEntity(body, Charset.forName("UTF-8"));
			entity.setContentEncoding("UTF-8");
			httpPost.setEntity(entity);

			CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

			jsonObject.put("code", httpResponse.getStatusLine().getStatusCode());
			jsonObject.put("message", EntityUtils.toString(httpResponse.getEntity()));
		} catch (Exception e) {
			// TODO: handle exception
			log.error("doPost Method Exception - " + url + headers + body + " - " + e.toString());
		}

		return jsonObject;
	}

	// 处理PUT消息
	public String doPut() {

		return null;
	}

	// 处理DELETE消息
	public String doDelete() {

		return null;
	}

	// 模拟LR，获取页面全部资源
	public String likeLR() {

		return null;
	}
}
